<?php

namespace App\Utils;

use App\Constants\ChannelTypeEnum;
use App\Constants\VivoEventTypeEnum;
use App\Model\Report\ReportThirdLog;
use App\Model\Report\VivoDevice;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Guzzle\ClientFactory;

class VivoUtil
{
    #[Inject]
    protected ClientFactory $clientFactory;

    public static function getReportTimeColumnByEventType($eventType): string
    {
        $map = [
            VivoEventTypeEnum::ACTIVATION->value => 'activation_time',
            VivoEventTypeEnum::NEXT_DAY->value   => 'next_day_time',
            VivoEventTypeEnum::REGISTER->value   => 'register_time',
        ];

        return $map[$eventType] ?? "";
    }

    public static function getReportStatusColumnByEventType($eventType): string
    {
        $map = [
            VivoEventTypeEnum::ACTIVATION->value => 'activation_status',
            VivoEventTypeEnum::NEXT_DAY->value   => 'next_day_status',
            VivoEventTypeEnum::REGISTER->value   => 'register_status',
        ];

        return $map[$eventType] ?? "";
    }

    /**
     * https://open-ad.vivo.com.cn/doc/index?id=217
     */
    public function reportEvent(VivoDevice $device, $ascribeChannel, $version, $packageName, $eventType)
    {
        // 不是生产环境，则忽略
        // if (!is_prod()) {
        //     return;
        // }

        $oaid = $device->oaid;

        $timestamp = ProjectUtil::getMillisecondTime();

        $reqUrl = "https://marketing-api.vivo.com.cn/openapi/v1/advertiser/behavior/upload"
            . '?access_token=' . $vivoAccessToken
            . '&timestamp=' . $timestamp
            . '&nonce=' . ProjectUtil::createRandomStringKey()
            . '&advertiser_id=' . $vivoAdvertiserId;

        $postData = [
            "srcType"  => 'APP',
            "pkgName"  => $packageName,
            "srcId"    => $vivoSrcId, // 数据源id,营销平台转化管理工具中新建，每个产品在每个账号下仅可新建一个
            "dataList" => [
                [
                    'userIdType' => 'OAID', // 用户标识类型,枚举值IMEI/IMEI_MD5/OAID/OAID_MD5/OTHER/OPENID,当数据源类型为APP时,该字段必传。
                    'userId'     => $oaid,
                    'cvType'     => $eventType,
                    'cvTime'     => $timestamp,
                    'requestId'  => $device->request_id,  // APP广告主：vivo回传点击数据时,透传给广告主的RequestID,使用点击归因的广告主需要回传。需对接vivo点击监测或第三方监测工具（取requestId字段）
                    'creativeId' => $device->creative_id, // APP广告主：vivo回传点击数据时,透传给广告主的creativeId,使用点击归因的广告主需要回传。需对接vivo点击监测第三方监测工具（取creativeId字段）。
                ]
            ],
        ];

        $ret = $this->clientFactory->create()->post($reqUrl, [
            'json' => $postData
        ])->getBody()->getContents();

        $retAry = json_decode($ret, true);

        ReportThirdLog::insertData($device->project_id, $device->app_id, ChannelTypeEnum::VIVO->value,
            $ascribeChannel, $version, $device->advertisement_id, $device->campaign_id, $oaid, $eventType, '', $postData,
            $retAry['code'] ?? '', $retAry);
    }
}